﻿using BLL.FKTZ;
using FKTZ.Models;
using Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using YQFK.Models;

namespace FKTZ.Controllers
{




    /// <summary>
    /// 10.访客台账
    /// </summary>
    public class FktzController : ApiController
    {
        private readonly FktzBLL _fktzBLL;
        private readonly FktzAttachmentBLL _FktzattachmentBLL;

        public FktzController()
        {
            _fktzBLL = new FktzBLL();
            _FktzattachmentBLL= new FktzAttachmentBLL();
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns>列表</returns>
        [Route("api/Fktz/GetList")]
        [HttpPost]
        public async Task<FktzPagingModelList<FktzModel>> GetList()
        {
            try
            {
                string filepath = Path.Combine(AppContext.BaseDirectory, "AppFile/Fktz");
                if (!Directory.Exists(filepath))
                    Directory.CreateDirectory(filepath);
                var provider = new MultipartFormDataStreamProvider(filepath);
                await Request.Content.ReadAsMultipartAsync(provider);
                var json = provider.FormData["json"];
                string res = json.ToString();
                dynamic dy = JsonConvert.DeserializeObject<ExpandoObject>(res);
                int pageSize = res.Contains("pageSize") ? Convert.ToInt32(dy.pageSize) : 0;
                int pageIndex = res.Contains("pageIndex") ? Convert.ToInt32(dy.pageIndex) : 0;
                string name = res.Contains("name") ? Convert.ToString(dy.name) : "";//人员姓名或事由
                string deptid = res.Contains("deptid") ? Convert.ToString(dy.deptid) : "";//部门ID
                DateTime ? startTime = res.Contains("startTime") && !string.IsNullOrEmpty(dy.startTime) ? Convert.ToDateTime(dy.startTime) : null;
                DateTime? endTime = res.Contains("endTime")&& !string.IsNullOrEmpty(dy.endTime) ? Convert.ToDateTime(dy.endTime) : null;
                var data = await _fktzBLL.ListAsync(deptid,name,startTime,endTime,pageSize, pageIndex);
                int total =(Int32)await _fktzBLL.ListAsync();
                return new FktzPagingModelList<FktzModel>() { Data = data, Code = 0, Count = total, Info = "获取数据成功" };
            }
            catch (Exception e)
            {
                return new FktzPagingModelList<FktzModel>() { Data = null, Code = -1, Count = 0, Info = e.ToString() };
            }

        }



        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>详情</returns>
        [Route("api/Fktz/Get")]
        [HttpGet]
        public async Task<FktzPagingModel<FktzModel>> Get(string id)
        {
            try
            {
                string filepath = HttpContext.Current.Request.ApplicationPath;
                var model = await _fktzBLL.GetAsync(id);
                var attachment = await _FktzattachmentBLL.GetAsync(id,"");
                if (attachment != null)
                {
                    List<FktzAttachmentModel> list = new List<FktzAttachmentModel>();
                    foreach (var item in attachment)
                    {
                        //item.Url = Url.Link("DefaultApi", new { controller = "Fktz", action = "GetFile" }) + "?id=" + item.AttachmentId;//下载路径
                        item.Url = Url.Content(filepath+ "/AppFile/Fktz/" + item.AttachmentId + item.FileName); //下载路径
                        list.Add(item);
                    }
                    model.Attachments = list;
                }

                return new FktzPagingModel<FktzModel>() { Data = model, Code = 0, Count = 0, Info = "获取数据成功" };
            }
            catch (Exception e)
            {
                return new FktzPagingModel<FktzModel>() { Data = null, Code = -1, Count = 0, Info = e.ToString() };
            }
        }


        /// <summary>
        /// 新增
        /// </summary>
        [Route("api/Fktz/FztzAdd")]
        [HttpPost]
        public async Task<Object> Post()
        {
            try
            {
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                string filepath = Path.Combine(AppContext.BaseDirectory, "AppFile/Fktz");
                if (!Directory.Exists(filepath))
                    Directory.CreateDirectory(filepath);
                var provider = new MultipartFormDataStreamProvider(filepath);
                await Request.Content.ReadAsMultipartAsync(provider);
                var json = provider.FormData["json"];

                var model = Newtonsoft.Json.JsonConvert.DeserializeObject<FktzModel>(json);
                model.FktzId = Guid.NewGuid().ToString();
                //增加附件
                foreach (MultipartFileData file in provider.FileData)
                {
                    var attachmentModel = new FktzAttachmentModel() { AttachmentId = Guid.NewGuid().ToString(), FileName = file.Headers.ContentDisposition.FileName.Trim(new char[] { '"' }), MediaType = file.Headers.ContentType.MediaType };
                    var fileinfo = new FileInfo(file.LocalFileName);
                    fileinfo.MoveTo(filepath+"\\"+ attachmentModel.AttachmentId + attachmentModel.FileName);
                    //using (var fs = fileinfo.OpenRead())
                    //{
                    //    attachmentModel.FileStream = new byte[fs.Length];
                    //    fs.Read(attachmentModel.FileStream, 0, attachmentModel.FileStream.Length);
                    //    fs.Flush();
                    //    fs.Close();
                    //}
                    if (model.Attachments == null)
                        model.Attachments = new List<FktzAttachmentModel>();

                    model.Attachments.Add(attachmentModel);

                    attachmentModel.Extension = attachmentModel.FileName.Substring(attachmentModel.FileName.LastIndexOf('.'));
                    File.Delete(file.LocalFileName);
                }


                string msg = string.Empty;
                if (!ModelState.IsValid)
                {
                    foreach (var v in ModelState.Values)
                    {
                        if (v.Errors.Count > 0)
                        {
                            foreach (var err in v.Errors)
                            {
                                msg = msg + err.ErrorMessage;
                            }
                        }
                    }
                    return new { code = -1, count = 0, info = "保存失败" + msg };
                }

                await _fktzBLL.CreateAsync(model);
                Created(nameof(Get), model);
                FktzModel data = new FktzModel();
                return new { code = 0, count = 0, info = "保存成功" };
            }
            catch (Exception e)
            {
                return new FktzPagingModel<FktzModel>() { Data = null, Code = -1, Count = 0, Info = e.ToString() };
            }

        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">内容</param>
        /// <returns></returns>
        /// <response code="200">编辑成功</response>
        /// <response code="400">如果找不到</response>
        /// <response code="500">验证失败</response>
        [Route("api/Fktz/FztzUpdate")]
        [HttpPost]
        public async Task<Object> Put([FromBody]FktzModel model)
        {
            if (!ModelState.IsValid) return new { code = 0, count = 0, info = "保存失败" };

            var data = await _fktzBLL.GetAsync(model.FktzId);
            if (data == null) return NotFound();

            await _fktzBLL.UpdateAsync(model);
            return new { code = 0, count = 0, info = "保存成功" };
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键</param>
        /// <response code="200">删除成功</response>
        /// <response code="400">如果找不到</response>
        [Route("api/Fktz/Delete")]
        [HttpGet]
        public async Task<Object> Delete(string id)
        {
            try
            {
                var data = await _fktzBLL.GetAsync(id);
                if (data == null) return NotFound();

                await _fktzBLL.DeleteAsync(id);
                return new { code = 0, count = 0, info = "保存成功" };
            }
            catch (Exception e)
            {
                return new FktzPagingModel<FktzModel>() { Data = null, Code = -1, Count = 0, Info = e.ToString() };
            }
        }
    }
}
